<template>
  <div style="margin: 0 20px">
    <!-- 头部查询、添加区域 -->
    <el-form ref="form">
      <el-form-item>
        <el-input
          v-model="username"
          placeholder="用户名"
          style="width: 200px; margin-right: 10px"
        ></el-input>
        <el-button type="primary" icon="el-icon-search" @click="queryUser"
          >查询</el-button
        >
        <el-button @click="clearUserName">清空</el-button>
      </el-form-item>
      <el-form-item>
        <!-- v-if="buttons.indexOf('btn.User.add') !== -1" 判断当前用户是否有操作添加用户按钮的权限 -->
        <el-button
          type="primary"
          @click="openDialog"
          v-if="buttons.indexOf('btn.User.add') !== -1"
          >添加</el-button
        >
        <el-button
          type="danger"
          :disabled="removeUserList.length < 1 ? true : false"
          @click="batchRemoveUser"
          >批量删除</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 展示数据区域 -->
    <el-table
      v-loading="loading"
      ref="multipleTable"
      tooltip-effect="dark"
      style="width: 100%"
      border
      :data="userList.items"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center">
      </el-table-column>
      <el-table-column type="index" label="序号" width="80" align="center">
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="120">
      </el-table-column>
      <el-table-column prop="nickName" label="用户昵称" width="120">
      </el-table-column>
      <el-table-column prop="roleName" label="权限列表" width="120">
      </el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间"> </el-table-column>
      <el-table-column prop="gmtModified" label="更新时间"> </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="{ row }">
          <el-button
            type="info"
            icon="el-icon-user"
            size="mini"
            title="分配角色"
            @click="openSetRoleDialog(row)"
          ></el-button>
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            title="修改用户"
            @click="openDialog(row)"
          ></el-button>
          <el-popconfirm
            :title="`确定删除${row.username}吗？`"
            style="margin-left: 10px"
            @onConfirm="removeUser(row)"
          >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              title="删除用户"
              slot="reference"
            ></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      :current-page="page"
      :page-sizes="[3, 5, 10, 20]"
      :page-size="limit"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="userList.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
    <!-- 添加|修改用户的对话框 -->
    <el-dialog
      :title="`${title}用户`"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-form
        :model="userInfo"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="userInfo.nickName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-show="isShowPassword">
          <el-input v-model="userInfo.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="roleDialogVisible" width="50%">
      <el-form ref="form" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="roleData.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="checkedCities"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              :label="role.id"
              v-for="role in roleList.allRolesList"
              :key="role.id"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateRoles" :loading="btnLoading"
          >确 定</el-button
        >
        <el-button @click="cancelSetRoles">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 引入深拷贝函数
import { Button } from "element-ui";
import cloneDeep from "lodash/cloneDeep";
import { mapState } from "vuex";
export default {
  name: "User",
  data() {
    return {
      // 头部文本框
      username: "",
      // 当前页
      page: 1,
      // 每页的条数
      limit: 5,
      // 加载效果
      loading: true,
      // 控制添加|修改用户对话框的显示与隐藏
      dialogVisible: false,
      // 对话框标题
      title: "",
      // 存储用户信息的对象, 发送给服务器
      userInfo: {
        username: "",
        password: "",
        username: "",
      },
      // 控制用户密码行的显示与隐藏
      isShowPassword: true,
      // 表单验证规则
      rules: {
        username: [
          { required: true, message: "用户名必须输入", trigger: "blur" },
          { min: 2, message: "用户名不能小于两位", trigger: "change" },
        ],
        password: [
          { required: true, message: "密码必须输入", trigger: "blur" },
          { min: 6, message: "密码不能小于六位", trigger: "change" },
        ],
      },
      // 要删除的用户列表
      removeUserList: [],
      // 控制分配角色对话框的显示与隐藏
      roleDialogVisible: false,
      // 控制全选按钮
      checkAll: false,
      // 表示 checkbox 的不确定状态，一般用于实现全选的效果
      isIndeterminate: false,
      // 分配角色要发送给服务器的数据
      roleData: {
        userId: "",
        username: "",
        roleIdList: [],
      },
      // 复选框选中组成的数组
      checkedCities: [],
      // 按钮的加载效果
      btnLoading: false,
    };
  },
  computed: {
    ...mapState("userStore", ["userList", "roleList"]),
    ...mapState("user", ["buttons"]),
  },
  watch: {
    roleList(newVal) {
      const arr = newVal.assignRoles || [];
      const allRolesList = newVal.allRolesList || [];
      // 获取用户本身就有的角色
      this.checkedCities = arr.map((item) => item.id);
      if (newVal === {}) {
        this.checkAll = false;
        this.isIndeterminate = false;
      } else {
        this.checkAll =
          this.checkedCities.length === allRolesList.length &&
          allRolesList.length > 0;
        this.isIndeterminate =
          this.checkedCities.length > 0 &&
          this.checkedCities.length < allRolesList.length;
      }
    },
  },
  methods: {
    // 获取用户数据
    async getUserList() {
      this.loading = true;
      try {
        // 派发actions
        await this.$store.dispatch("userStore/getUserList", {
          page: this.page,
          limit: this.limit,
          username: this.username,
        });
        this.loading = false;
      } catch (error) {}
    },
    // 每页的条数发生变化时的回调
    handleSizeChange(limit) {
      this.limit = limit;
      this.page = 1;
      // 重新获取用户数据
      this.getUserList();
    },
    // 当前页发生变化时的回调
    handleCurrentChange(page) {
      this.page = page;
      // 重新获取用户数据
      this.getUserList();
    },
    // 根据输入的用户名,查询用户
    queryUser() {
      this.page = 1;
      // 重新获取用户数据
      this.getUserList();
    },
    // 清空文本框
    clearUserName() {
      this.username = "";
      this.page = 1;
      // 重新获取用户数据
      this.getUserList();
    },
    // 添加用户|修改用户
    openDialog(row = {}) {
      if (row.id) {
        this.isShowPassword = false;
      } else {
        this.isShowPassword = true;
      }
      // 开启对话框
      this.dialogVisible = true;
      this.userInfo = cloneDeep(row);
    },
    // 取消添加|修改
    cancel() {
      // 清空
      this.userInfo = {};
      // 关闭对话框
      this.dialogVisible = false;
      // 清空表单验证警告
      this.$refs.ruleForm.resetFields();
    },
    // 添加用户|修改用户
    addOrUpdateUser() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          try {
            // 派发actions
            await this.$store.dispatch(
              "userStore/addOrUpdateUser",
              this.userInfo
            );
            // 成功的提示
            this.$message({
              message: "保存成功",
              type: "success",
            });
            // 重新获取用户信息
            this.getUserList();
            // 关闭对话框
            this.dialogVisible = false;
          } catch (error) {
            // 错误的提示
            this.$message({
              message: "保存失败",
              type: "error",
            });
          }
        } else {
          return false;
        }
      });
    },
    // 改变复选框的回调
    handleSelectionChange(data) {
      // 赋值
      this.removeUserList = data.map((item) => item.id);
    },
    // 批量删除用户的回调
    batchRemoveUser() {
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            // 派发actions
            await this.$store.dispatch(
              "userStore/batchRemoveUser",
              this.removeUserList
            );
            // 成功提示信息
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            // 重新获取用户数据
            this.page = 1;
            this.getUserList();
          } catch (error) {
            // 失败提示信息
            this.$message({
              type: "error",
              message: "删除失败!",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 删除用户
    async removeUser(row) {
      try {
        // 派发actions
        await this.$store.dispatch("userStore/reomveUser", row.id);
        // 成功提示信息
        this.$message({
          message: "删除成功",
          type: "success",
        });
        // 当删除的用户刚好是当前页的最后一个时, 页数往前移一位
        if (this.userList.items.length < 1) {
          this.page = this.page - 1;
        }
        // 重新获取用户数据
        this.getUserList();
      } catch (error) {
        // 失败提示信息
        this.$message({
          message: "删除失败",
          type: "error",
        });
      }
    },
    // 打开分配角色的对话框
    openSetRoleDialog(row) {
      this.roleDialogVisible = true;
      this.roleData.username = row.username;
      this.roleData.userId = row.id;
      // 派发获取角色列表的actions
      this.$store.dispatch("userStore/getRoleList", row.id);
    },
    // 全选复选框点击时的回调
    handleCheckAllChange(bool) {
      const arr = this.roleList.allRolesList || [];
      const roleIdList = arr.map((item) => item.id);
      this.checkedCities = bool ? roleIdList : [];
      this.isIndeterminate = false;
    },
    // 每个角色复选框被点击时的回调
    handleCheckedCitiesChange(value) {
      // 获取选中的角色数组的长度
      let checkedCount = value.length;
      // 让全选按钮动态变化
      this.checkAll = checkedCount === this.roleList.allRolesList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.roleList.allRolesList.length;
    },
    // 取消分配角色
    cancelSetRoles() {
      this.roleDialogVisible = false;
      // 清空选中的数组
      this.checkedCities = [];
      // 派发commit，清空roleList数据
      this.$store.commit("userStore/CLEAR");
    },
    // 保存分配角色
    async updateRoles() {
      this.btnLoading = true;
      // 整合数据
      this.roleData.roleIdList = this.checkedCities;
      try {
        // 派发actions
        await this.$store.dispatch("userStore/updateRoles", this.roleData);
        // 关闭加载效果
        this.btnLoading = false;
        // 成功提示信息
        this.$message({
          message: "保存成功",
          type: "success",
        });
        // 派发commit，清空roleList
        this.$store.commit("userStore/CLEAR");
        // 重新获取用户数据
        this.getUserList();
        // 关闭对话框
        this.roleDialogVisible = false;
      } catch (error) {
        // 失败提示信息
        this.$message({
          message: "保存失败",
          type: "error",
        });
      }
    },
  },
  mounted() {
    this.getUserList();
  },
};
</script>

<style>
</style>